package com.homson.servicedomain.factory;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;

@Component
public abstract class AbstractFactory<K,V> implements ApplicationContextAware {
    
    private ApplicationContext applicationContext;
    
    private Map<K,V> beanGroup= Collections.emptyMap();
    
    public abstract Class<V> getClazz();
    
    public abstract Function<V,K> vkFunction();
    
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        
        this.applicationContext=applicationContext;
    
        Map<String, V> beans = applicationContext.getBeansOfType(getClazz());
        List<V> beanList=new ArrayList<>();
        if(!beans.isEmpty()){
            beanList.addAll(beans.values());
        }
        beanGroup=new HashMap<>(beanList.size());
        for(V bean:beans.values()){
            if(bean==null)
                continue;
            K key = vkFunction().apply(bean);
            beanGroup.put(key,bean);
        }
    }
    
    public Optional<V> findBean(K key){
        return Optional.ofNullable(beanGroup.get(key));
    }
    
}
